package com.tencent.live.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.squareup.picasso.Transformation;

/**
 * 裁剪上面一部分，需要传入输出宽高
 * Created by danao on 2018/4/23.
 */

public class TopTransform implements Transformation {

    private int outputWidth;
    private int outputHeight;

    public TopTransform(int width, int height) {
        this.outputWidth = width;
        this.outputHeight = height;
    }

    @Override
    public Bitmap transform(Bitmap source) {
        int height = outputHeight * source.getWidth() / outputWidth;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), height);
        if (squaredBitmap != source) {
            source.recycle();//回收垃圾
        }

        Bitmap bitmap = Bitmap.createBitmap(source.getWidth(), height, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap,
                BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);//定义一个渲染器
        paint.setShader(shader);//设置渲染器
        paint.setAntiAlias(true);

        canvas.drawRect(0,0, source.getWidth(), height, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "top";
    }
}
